import React, { useEffect, useState } from 'react';
import { Table, TableProps } from 'antd';
import { BaseColumn } from './columns';
import './BaseTable.css';

interface BaseTableProps extends Omit<TableProps<any>, 'columns'> {
  columns: any[]; // 支持直接传入渲染后的列配置
  renderColumns?: (columns: BaseColumn[]) => any[]; // 可选的渲染函数
}

const BaseTable: React.FC<BaseTableProps> = ({
  columns,
  renderColumns,
  className = '',
  ...props
}) => {
  const [scrollbarWidth, setScrollbarWidth] = useState(0);

  // 检测滚动条宽度
  useEffect(() => {
    const detectScrollbarWidth = () => {
      const outer = document.createElement('div');
      outer.style.visibility = 'hidden';
      outer.style.overflow = 'scroll';
      (outer.style as any).msOverflowStyle = 'scrollbar';
      document.body.appendChild(outer);

      const inner = document.createElement('div');
      outer.appendChild(inner);

      const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;
      document.body.removeChild(outer);

      return scrollbarWidth;
    };

    const width = detectScrollbarWidth();
    setScrollbarWidth(width);
    
    // 设置CSS变量供样式使用
    document.documentElement.style.setProperty('--scrollbar-width', `${width}px`);
  }, []);

  // 处理列配置 - 支持直接传入渲染后的列或使用renderColumns函数
  let antdColumns;
  let totalWidth = 0;

  if (renderColumns && typeof renderColumns === 'function') {
    // 使用renderColumns函数处理BaseColumn[]类型
    const baseColumns = columns as BaseColumn[];
    totalWidth = baseColumns.reduce((sum, col) => sum + col.width, 0);
    
    antdColumns = renderColumns(baseColumns).map((col, index) => {
      const baseCol = baseColumns[index];
      return {
        ...col,
        width: baseCol.width,
        className: `base-table-cell ${baseCol.className || ''}`,
        ellipsis: baseCol.ellipsis !== false,
        onHeaderCell: () => ({
          style: {
            width: `${baseCol.width}px`,
            minWidth: `${baseCol.width}px`,
            maxWidth: `${baseCol.width}px`,
            padding: '12px 16px',
            fontWeight: 600,
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            overflow: 'hidden',
            boxSizing: 'border-box'
          }
        }),
        onCell: () => ({
          style: {
            width: `${baseCol.width}px`,
            minWidth: `${baseCol.width}px`,
            maxWidth: `${baseCol.width}px`,
            padding: '12px 16px',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            overflow: 'hidden',
            boxSizing: 'border-box'
          }
        })
      };
    });
  } else {
    // 直接使用已渲染的列配置
    antdColumns = columns;
    // 尝试从列配置中提取宽度信息
    totalWidth = columns.reduce((sum, col) => {
      const width = col.width || 150; // 默认宽度
      return sum + width;
    }, 0);
  }

  // 确保dataSource是数组
  const safeDataSource = Array.isArray(props.dataSource) ? props.dataSource : [];
  
  return (
    <div className="base-table-wrapper">
      <Table
        {...props}
        dataSource={safeDataSource}
        columns={antdColumns}
        className={`base-table ${className}`}
        tableLayout="fixed"
        sticky={{
          offsetHeader: 0
        }}
        scroll={{
          x: totalWidth,
          y: 'calc(100vh - 320px)'
        }}
        pagination={{
          pageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          ...props.pagination
        }}
      />
    </div>
  );
};

export default BaseTable;